package com.budwk.app.jim.server;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZY.Wang
 * @since 2023/6/15
 */
public class JimJwtTokenUtils {

    private final static String field_user_name = "userName";
    private final static String field_user_id = "userId";

    private final static String secret = "Tr0NwgD8d425K0Fu7snVtpEoMDU6mvp";

    public static String createJwtToken(String userId, String userName) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(field_user_name, userName);
        claims.put(field_user_id, userId);
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    public static JimJwtUserInfoBO getInfoByToken(String token) {
        if (StringUtils.isNotBlank(token)) {
            try {
                Claims claims = parseToken(token);
                String userId = (String) claims.get(field_user_id);
                String userName = (String) claims.get(field_user_name);

                return new JimJwtUserInfoBO(userId, userName);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static void main(String[] args) {
        String jwtToken = createJwtToken("7614d177bce64528922140a2d472e189", "17585379278");
        System.out.println(jwtToken);
    }
}
